home *** CD-ROM | disk | FTP | other *** search
/ Game.EXE 2001 January / Game.EXE_01_2001.iso / demos / Blade of Darkness / data1.cab / Program_Executable_Files / Lib / PythonLib / rexec.py < prev    next >
Encoding:
Python Source  |  2000-11-16  |  11.9 KB  |  384 lines

  1. """Restricted execution facilities.
  2.  
  3. The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
  4. r_import(), which correspond roughly to the built-in operations
  5. exec, eval(), execfile() and import, but executing the code in an
  6. environment that only exposes those built-in operations that are
  7. deemed safe.  To this end, a modest collection of 'fake' modules is
  8. created which mimics the standard modules by the same names.  It is a
  9. policy decision which built-in modules and operations are made
  10. available; this module provides a reasonable default, but derived
  11. classes can change the policies e.g. by overriding or extending class
  12. variables like ok_builtin_modules or methods like make_sys().
  13.  
  14. XXX To do:
  15. - r_open should allow writing tmp dir
  16. - r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)
  17.  
  18. """
  19.  
  20.  
  21. import sys
  22. import __builtin__
  23. import os
  24. import ihooks
  25.  
  26.  
  27. class FileBase:
  28.  
  29.     ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
  30.             'readlines', 'seek', 'tell', 'write', 'writelines')
  31.  
  32.  
  33. class FileWrapper(FileBase):
  34.  
  35.     # XXX This is just like a Bastion -- should use that!
  36.  
  37.     def __init__(self, f):
  38.         self.f = f
  39.         for m in self.ok_file_methods:
  40.             if not hasattr(self, m) and hasattr(f, m):
  41.                 setattr(self, m, getattr(f, m))
  42.  
  43.     def close(self):
  44.         self.flush()
  45.  
  46.  
  47. TEMPLATE = """
  48. def %s(self, *args):
  49.         return apply(getattr(self.mod, self.name).%s, args)
  50. """
  51.  
  52. class FileDelegate(FileBase):
  53.  
  54.     def __init__(self, mod, name):
  55.         self.mod = mod
  56.         self.name = name
  57.  
  58.     for m in FileBase.ok_file_methods + ('close',):
  59.         exec TEMPLATE % (m, m)
  60.  
  61.  
  62. class RHooks(ihooks.Hooks):
  63.  
  64.     def __init__(self, *args):
  65.         # Hacks to support both old and new interfaces:
  66.         # old interface was RHooks(rexec[, verbose])
  67.         # new interface is RHooks([verbose])
  68.         verbose = 0
  69.         rexec = None
  70.         if args and type(args[-1]) == type(0):
  71.             verbose = args[-1]
  72.             args = args[:-1]
  73.         if args and hasattr(args[0], '__class__'):
  74.             rexec = args[0]
  75.             args = args[1:]
  76.         if args:
  77.             raise TypeError, "too many arguments"
  78.         ihooks.Hooks.__init__(self, verbose)
  79.         self.rexec = rexec
  80.  
  81.     def set_rexec(self, rexec):
  82.         # Called by RExec instance to complete initialization
  83.         self.rexec = rexec
  84.  
  85.     def is_builtin(self, name):
  86.         return self.rexec.is_builtin(name)
  87.  
  88.     def init_builtin(self, name):
  89.         m = __import__(name)
  90.         return self.rexec.copy_except(m, ())
  91.  
  92.     def init_frozen(self, name): raise SystemError, "don't use this"
  93.     def load_source(self, *args): raise SystemError, "don't use this"
  94.     def load_compiled(self, *args): raise SystemError, "don't use this"
  95.  
  96.     def load_dynamic(self, name, filename, file):
  97.         return self.rexec.load_dynamic(name, filename, file)
  98.  
  99.     def add_module(self, name):
  100.         return self.rexec.add_module(name)
  101.  
  102.     def modules_dict(self):
  103.         return self.rexec.modules
  104.  
  105.     def default_path(self):
  106.         return self.rexec.modules['sys'].path
  107.  
  108.  
  109. class RModuleLoader(ihooks.FancyModuleLoader):
  110.  
  111.     def load_module(self, name, stuff):
  112.         file, filename, info = stuff
  113.         m = ihooks.FancyModuleLoader.load_module(self, name, stuff)
  114.         m.__filename__ = filename
  115.         return m
  116.  
  117.  
  118. class RModuleImporter(ihooks.ModuleImporter):
  119.  
  120.     def reload(self, module, path=None):
  121.         if path is None and hasattr(module, '__filename__'):
  122.             head, tail = os.path.split(module.__filename__)
  123.             path = [os.path.join(head, '')]
  124.         return ihooks.ModuleImporter.reload(self, module, path)
  125.  
  126.  
  127. class RExec(ihooks._Verbose):
  128.  
  129.     """Restricted Execution environment."""
  130.  
  131.     ok_path = tuple(sys.path)           # That's a policy decision
  132.  
  133.     ok_builtin_modules = ('audioop', 'array', 'binascii',
  134.                           'cmath', 'errno', 'imageop',
  135.                           'marshal', 'math', 'md5', 'operator',
  136.                           'parser', 'regex', 'pcre', 'rotor', 'select',
  137.                           'strop', 'struct', 'time')
  138.  
  139.     ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
  140.                       'stat', 'times', 'uname', 'getpid', 'getppid',
  141.                       'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')
  142.  
  143.     ok_sys_names = ('ps1', 'ps2', 'copyright', 'version',
  144.                     'platform', 'exit', 'maxint')
  145.  
  146.     nok_builtin_names = ('open', 'reload', '__import__')
  147.  
  148.     def __init__(self, hooks = None, verbose = 0):
  149.         ihooks._Verbose.__init__(self, verbose)
  150.         # XXX There's a circular reference here:
  151.         self.hooks = hooks or RHooks(verbose)
  152.         self.hooks.set_rexec(self)
  153.         self.modules = {}
  154.         self.ok_dynamic_modules = self.ok_builtin_modules
  155.         list = []
  156.         for mname in self.ok_builtin_modules:
  157.             if mname in sys.builtin_module_names:
  158.                 list.append(mname)
  159.         self.ok_builtin_modules = tuple(list)
  160.         self.set_trusted_path()
  161.         self.make_builtin()
  162.         self.make_initial_modules()
  163.         # make_sys must be last because it adds the already created
  164.         # modules to its builtin_module_names
  165.         self.make_sys()
  166.         self.loader = RModuleLoader(self.hooks, verbose)
  167.         self.importer = RModuleImporter(self.loader, verbose)
  168.  
  169.     def set_trusted_path(self):
  170.         # Set the path from which dynamic modules may be loaded.
  171.         # Those dynamic modules must also occur in ok_builtin_modules
  172.         self.trusted_path = filter(os.path.isabs, sys.path)
  173.  
  174.     def load_dynamic(self, name, filename, file):
  175.         if name not in self.ok_dynamic_modules:
  176.             raise ImportError, "untrusted dynamic module: %s" % name
  177.         if sys.modules.has_key(name):
  178.             src = sys.modules[name]
  179.         else:
  180.             import imp
  181.             src = imp.load_dynamic(name, filename, file)
  182.         dst = self.copy_except(src, [])
  183.         return dst
  184.  
  185.     def make_initial_modules(self):
  186.         self.make_main()
  187.         self.make_osname()
  188.  
  189.     # Helpers for RHooks
  190.  
  191.     def is_builtin(self, mname):
  192.         return mname in self.ok_builtin_modules
  193.  
  194.     # The make_* methods create specific built-in modules
  195.  
  196.     def make_builtin(self):
  197.         m = self.copy_except(__builtin__, self.nok_builtin_names)
  198.         m.__import__ = self.r_import
  199.         m.reload = self.r_reload
  200.         m.open = self.r_open
  201.  
  202.     def make_main(self):
  203.         m = self.add_module('__main__')
  204.  
  205.     def make_osname(self):
  206.         osname = os.name
  207.         src = __import__(osname)
  208.         dst = self.copy_only(src, self.ok_posix_names)
  209.         dst.environ = e = {}
  210.         for key, value in os.environ.items():
  211.             e[key] = value
  212.  
  213.     def make_sys(self):
  214.         m = self.copy_only(sys, self.ok_sys_names)
  215.         m.modules = self.modules
  216.         m.argv = ['RESTRICTED']
  217.         m.path = map(None, self.ok_path)
  218.         m = self.modules['sys']
  219.         l = self.modules.keys() + list(self.ok_builtin_modules)
  220.         l.sort()
  221.         m.builtin_module_names = tuple(l)
  222.  
  223.     # The copy_* methods copy existing modules with some changes
  224.  
  225.     def copy_except(self, src, exceptions):
  226.         dst = self.copy_none(src)
  227.         for name in dir(src):
  228.             setattr(dst, name, getattr(src, name))
  229.         for name in exceptions:
  230.             try:
  231.                 delattr(dst, name)
  232.             except AttributeError:
  233.                 pass
  234.         return dst
  235.  
  236.     def copy_only(self, src, names):
  237.         dst = self.copy_none(src)
  238.         for name in names:
  239.             try:
  240.                 value = getattr(src, name)
  241.             except AttributeError:
  242.                 continue
  243.             setattr(dst, name, value)
  244.         return dst
  245.  
  246.     def copy_none(self, src):
  247.         return self.add_module(src.__name__)
  248.  
  249.     # Add a module -- return an existing module or create one
  250.  
  251.     def add_module(self, mname):
  252.         if self.modules.has_key(mname):
  253.             return self.modules[mname]
  254.         self.modules[mname] = m = self.hooks.new_module(mname)
  255.         m.__builtins__ = self.modules['__builtin__']
  256.         return m
  257.  
  258.     # The r* methods are public interfaces
  259.  
  260.     def r_exec(self, code):
  261.         m = self.add_module('__main__')
  262.         exec code in m.__dict__
  263.  
  264.     def r_eval(self, code):
  265.         m = self.add_module('__main__')
  266.         return eval(code, m.__dict__)
  267.  
  268.     def r_execfile(self, file):
  269.         m = self.add_module('__main__')
  270.         return execfile(file, m.__dict__)
  271.  
  272.     def r_import(self, mname, globals={}, locals={}, fromlist=[]):
  273.         return self.importer.import_module(mname, globals, locals, fromlist)
  274.  
  275.     def r_reload(self, m):
  276.         return self.importer.reload(m)
  277.  
  278.     def r_unload(self, m):
  279.         return self.importer.unload(m)
  280.     
  281.     # The s_* methods are similar but also swap std{in,out,err}
  282.  
  283.     def make_delegate_files(self):
  284.         s = self.modules['sys']
  285.         self.delegate_stdin = FileDelegate(s, 'stdin')
  286.         self.delegate_stdout = FileDelegate(s, 'stdout')
  287.         self.delegate_stderr = FileDelegate(s, 'stderr')
  288.         self.restricted_stdin = FileWrapper(sys.stdin)
  289.         self.restricted_stdout = FileWrapper(sys.stdout)
  290.         self.restricted_stderr = FileWrapper(sys.stderr)
  291.  
  292.     def set_files(self):
  293.         if not hasattr(self, 'save_stdin'):
  294.             self.save_files()
  295.         if not hasattr(self, 'delegate_stdin'):
  296.             self.make_delegate_files()
  297.         s = self.modules['sys']
  298.         s.stdin = self.restricted_stdin
  299.         s.stdout = self.restricted_stdout
  300.         s.stderr = self.restricted_stderr
  301.         sys.stdin = self.delegate_stdin
  302.         sys.stdout = self.delegate_stdout
  303.         sys.stderr = self.delegate_stderr
  304.  
  305.     def reset_files(self):
  306.         self.restore_files()
  307.         s = self.modules['sys']
  308.         self.restricted_stdin = s.stdin
  309.         self.restricted_stdout = s.stdout
  310.         self.restricted_stderr = s.stderr
  311.         
  312.  
  313.     def save_files(self):
  314.         self.save_stdin = sys.stdin
  315.         self.save_stdout = sys.stdout
  316.         self.save_stderr = sys.stderr
  317.  
  318.     def restore_files(self):
  319.         sys.stdin = self.save_stdin
  320.         sys.stdout = self.save_stdout
  321.         sys.stderr = self.save_stderr
  322.     
  323.     def s_apply(self, func, args=(), kw=None):
  324.         self.save_files()
  325.         try:
  326.             self.set_files()
  327.             if kw:
  328.                 r = apply(func, args, kw)
  329.             else:
  330.                 r = apply(func, args)
  331.         finally:
  332.             self.restore_files()
  333.     
  334.     def s_exec(self, *args):
  335.         self.s_apply(self.r_exec, args)
  336.     
  337.     def s_eval(self, *args):
  338.         self.s_apply(self.r_eval, args)
  339.     
  340.     def s_execfile(self, *args):
  341.         self.s_apply(self.r_execfile, args)
  342.     
  343.     def s_import(self, *args):
  344.         self.s_apply(self.r_import, args)
  345.     
  346.     def s_reload(self, *args):
  347.         self.s_apply(self.r_reload, args)
  348.     
  349.     def s_unload(self, *args):
  350.         self.s_apply(self.r_unload, args)
  351.     
  352.     # Restricted open(...)
  353.     
  354.     def r_open(self, file, mode='r', buf=-1):
  355.         if mode not in ('r', 'rb'):
  356.             raise IOError, "can't open files for writing in restricted mode"
  357.         return open(file, mode, buf)
  358.  
  359.  
  360. def test():
  361.     import traceback
  362.     r = RExec(verbose=('-v' in sys.argv[1:]))
  363.     print "*** RESTRICTED *** Python", sys.version
  364.     print sys.copyright
  365.     while 1:
  366.         try:
  367.             try:
  368.                 s = raw_input('>>> ')
  369.             except EOFError:
  370.                 print
  371.                 break
  372.             if s and s[0] != '#':
  373.                 s = s + '\n'
  374.                 c = compile(s, '<stdin>', 'single')
  375.                 r.r_exec(c)
  376.         except SystemExit, n:
  377.             sys.exit(n)
  378.         except:
  379.             traceback.print_exc()
  380.  
  381.  
  382. if __name__ == '__main__':
  383.     test()
  384.